<?php

class CAccount extends Zend_Db_Table{
	
	protected $_name;
	
	protected $_primary;

	public function __construct(){
		
		$this->_name=R_PRE."accounts";
		
		$this->_primary="accountid";
		
		parent::__construct();
		
	}

	public function createAccount($data){
		
		$accountid=$this->insert($data);
	
		return $accountid;
		
	}
	
	public function editAccount($accountid,$data){
		
		$db=$this->getAdapter();
		
		$where = $db->quoteInto('accountid = ?', $accountid);
		
		$rows_affected=$db->update($this->_name,$data,$where);
		
		if($rows_affected!=1){
			
			return false;
			
		}else{
			
			return true;
			
		}
		
		
	}
	
	public function delAccount($accountidArray){
		
		$db=$this->getAdapter();
		
		$accountidString=join(',',$accountidArray);
		
		$result=$db->query("DELETE FROM $this->_name WHERE accountid IN ($accountidString)");
		
		return $result;
		
	}
	
	public function delAccountBySign($sign){
		
		$sign=(array)$sign;
		
		$db=$this->getAdapter();
		
		$signString=join(',',$sign);
		
		$result=$db->query("DELETE FROM $this->_name WHERE sign IN ($signString)");
		
		return $result;
		
	}
	
	public function getDetail($accountid){
		
		$db=$this->getAdapter();
		
		$select = $db->select();

		$select->from($this->_name);
		
		$select->where('accountid = ? ',$accountid);
		
		return $db->fetchAll($select);
		
	}
	
	public function getAccountDetails($fieldArray=null){
		
		$db=$this->getAdapter();
		
		$whereString=null;
		
		if($fieldArray!=null){
		
			$where=array();
			
			foreach ($fieldArray as $field => $value){
				
				$where[]= $db->quoteInto("$field = ?", $value);
				
			}
			
			$whereString=join(' AND ',$where);
		
		}
		
		$row=$this->fetchAll($whereString);
		
		if($row!=null){
	
			return $row->toArray();
			
       	}else{
       		
       		return array();
       		
       	}
		
	}
	
	public function getAllAccountCounts($where=''){
		
		$db=$this->getAdapter();
		
		$select = $db->select();

		$select->from($this->_name,'COUNT(*)');
		
		if($where!=''){
			
			$select->where($where);
	
		}
		
		return $db->fetchOne($select);
		
	}
	
	public function getAllAccounts($from,$counts,$where=''){
		
		$db=$this->getAdapter();
		
		$select = $db->select();
		
		$select->from($this->_name,'*');
		
		$typeFlTable=R_PRE.'accountfls';

		$select->joinLeft($typeFlTable, "$this->_name.flid = $typeFlTable.flid", '*');
		
		$select->joinLeft(R_PRE.'members AS A', "A.uid = $this->_name.from_uid", array('from_username'=>'A.username'));
		
		$select->joinLeft(R_PRE.'members AS B', "B.uid = $this->_name.to_uid", array('to_username'=>'B.username'));
		
		if($where!=''){
			
			$select->where($where);
			
		}	
		
		$select->order("add_time DESC");
		
		if($counts!=0){
		
			$select->limit($counts, $from);
		
		}
		
		return $db->fetchAll($select);
		
	}
	
}